#include "PMTContainer.hh"
#include "YamlConfiger.hh"
#include <sstream>

PMTContainer* PMTContainer::m_Instance = nullptr;

PMTContainer::PMTContainer()
{
    YAML::Node configer = (*YamlConfiger::GetInstance()->GetConfiger())["PMT"];
    if(configer["Default"].IsDefined())
    {
        for (auto it = configer.begin(); it != configer.end(); ++it)
        {
            std::string pMTName = it->first.as<std::string>();
            if (pMTName.find("PMT") == 0)
            {
                for (auto itd = configer["Default"].begin(); itd != configer["Default"].end(); ++itd)
                {
                    std::string key = itd->first.as<std::string>();
                    if (!configer[pMTName][key].IsDefined())
                    {
                        configer[pMTName][key] = itd->second;
                    }
                }
            }
        }
    }
    m_NumOfPMT = configer["NumOfPMT"].as<int>();
    for (int i = 1; i <= m_NumOfPMT; ++i)
    {
        std::ostringstream name;
        name << "PMT" << i;
        m_VPMT.push_back(new PMT(i, configer[name.str()]));
    }
}

PMTContainer::~PMTContainer()
{
    for(auto ptrPMT:m_VPMT)
    {
        delete ptrPMT;
    }
}

const PMT* PMTContainer::GetPMT(Int_t i) const
{
    if (i >= m_NumOfPMT)
    {
        std::cout << "Error! request PMT number out of boundary." << std::endl; 
        return nullptr;
    }
    return m_VPMT[i];
}

void PMTContainer::ProcessEvent(aSimEvent& aEvent)
{
    for(auto ptrPMT:m_VPMT)
    {
        ptrPMT->ClearVPhoton();
    }

    for(auto aPhoton:aEvent.VSimPhoton)
    {
        Int_t iPMT = -1;
        Double_t minDis = 1e10;
        for (int i = 0; i < m_NumOfPMT; ++i)
        {
            PMT* ptrPMT = m_VPMT[i];
            Double_t dis = m_VPMT[i]->Distance(aPhoton.Pos);
            if(dis < minDis)
            {
                iPMT = i;
                minDis = dis;
            }
        }
        m_VPMT[iPMT]->ClassifyNewPhoton(aPhoton);
    }
    for(auto ptrPMT:m_VPMT)
    {
        ptrPMT->Processing();
    }
}